﻿using NewRen.Models;
using NewRen.Schemas;
using PagedList;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{

    /// <summary>
    ///  系统图片管理
    /// </summary>
    [Schema.LoginCheck]
    public class PictureController : BaseController
    {
        // GET: Admin/Images
        public ActionResult Index(int page = 1)
        {
            var pictures = db.Pictures.OrderByDescending(p => p.Time).ToPagedList(page, 20);
            return View(pictures);
        }

        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }


        /// <summary>
        /// 增加系统图片
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Add(Picture model, HttpPostedFileBase file)
        {
            if (file != null)
            {
                try
                {
                    string random = Helpers.DateHelper.GetTimeStamp();
                    Picture picture = new Picture();

                    picture.ContentType = file.ContentType;
                    picture.Title = model.Title;
                    picture.Time = DateTime.Now;

                    string root = "~/Pictures/";
                    var phicyPath = HostingEnvironment.MapPath(root);
                    Directory.CreateDirectory(phicyPath);
                    file.SaveAs(phicyPath + random + Path.GetExtension(file.FileName));
                    picture.Path = "/Pictures/" + random + Path.GetExtension(file.FileName);
                    db.Pictures.Add(picture);
                    db.SaveChanges();
                    return Redirect("/Admin/Picture/Index");
                }
                catch
                {
                    ModelState.AddModelError("", "增加图片出错！");
                }

            }
            else
            {
                ModelState.AddModelError("", "你没有选择图片，请选择图片");
            }
            return View();
        }


        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult Delete(int id)
        {
            try
            {
                var picture = db.Pictures.Find(id);
                var phicyPath = HostingEnvironment.MapPath(picture.Path);
                System.IO.File.Delete(phicyPath);
                db.Pictures.Remove(picture);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("err");
            }
        }



    }
}